import { boot } from 'quasar/wrappers'
import axios from 'axios'
import { Notify } from 'quasar'
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({ baseURL: 'http://127.0.0.1:8000' })

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})
//1 使用axios前置拦截器，让所有的请求都携带token
axios.interceptors.request.use(config=>{
  //携带token
  let uToken =  localStorage.getItem("token");
  if(uToken){
    //我就在请求头里面添加一个头信息叫做U-TOKEN ==》jsessionid(token) 后台通过token作为key值可以在redis中获得loginUser的信息
    config.headers['U-TOKEN']=uToken;
  }
  return config;
},error => {
  Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  if(response.data.code===200) {
    return response.data.data
  }else{
    Notify.create({
      color: "red",
      textColor: "white",
      icon: "error",
      message: JSON.stringify(response.data.msg),
      position: "top-right",
      timeout: Math.random() * 5000 + 3000
    })
    return Promise.reject(response.data);
  }
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
  return response;
}, function (error) {
  Notify.create({
    color: "red",
    textColor: "white",
    icon: "error",
    message: JSON.stringify(error.response.msg),
    position: "top-right",
    timeout: Math.random() * 5000 + 3000
  })
  return Promise.reject(error);
});
export { api }
